package com.hmall.gateway.filter;

import lombok.Data;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 自定义网关过滤器工厂
 * 用于在请求处理过程中打印参数信息
 */
@Component
public class PrintAnyGatewayFilterFactory extends AbstractGatewayFilterFactory<PrintAnyGatewayFilterFactory.Config> {
    
    /**
     * 构造函数，必须调用父类构造函数并传入配置类
     */
    public PrintAnyGatewayFilterFactory() {
        super(Config.class);
    }

    /**
     * 定义配置文件中参数的顺序
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return List.of("name", "value");
    }

    /**
     * 定义过滤器的核心逻辑
     */
    @Override
    public GatewayFilter apply(Config config) {
       return new OrderedGatewayFilter(new GatewayFilter() {
           @Override
           public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
               System.out.println("PrintAnyGatewayFilterFactory--------------");

               // 接收来自配置文件中的参数
               String name = config.getName();
               System.out.println("获得的name的值为：" + name);
               String value = config.getValue();
               System.out.println("获得的value的值为：" + value);
               return chain.filter(exchange);
           }
       }, 100);  // 数字越小优先级越高
    }

    /**
     * 配置类，用于接收配置参数
     */
    @Data
    public static class Config {
        private String name;
        private String value;
    }
}
